import React, { useState, useEffect } from 'react';
import { history, connect } from 'umi'
import pageTabUtil from '@/utils/pageTabUtil';
import { Icon, Button, Menu, Card, Spin, message, notification } from 'antd';
import _ from 'lodash';
import { eventTrack } from '@/utils/track';
import { MailingList, MailContent, MailSwitchBar, MailBindForm } from './components';
import styles from './styles.less';
import { useMailList, useSetMailRead, usePullList } from './hooks';

// 我的邮件首页
const MailList = ({ user, mailBindList, dispatch, mailPromptCount }) => {
    const { userCode } = user; // 获取登陆用户信息

    const [mailListData, setMailListData] = useState([]); // 邮件列表数据源
    const [mailId, setMailId] = useState(null); // 详情的id
    const [infoSubject, setInfoSubject] = useState(null); // 详情的主题
    const [visible, setVisible] = useState(false);

    const [currentMail, setCurrentMail] = useState(localStorage.getItem('currentMail')); // 当前选中的邮箱

    const [params, setparams] = useState({
        mailType: 'in',
        belongs: currentMail,
        pageNo: 1,
        pageSize: 20
    });

    // 页面一开始载入显示收件箱第一页的数据
    const { mailListLoading, mailListResData, mailListTotal, setMailListResData } = useMailList(params); // 拉取收件箱或者发件箱的数据
    useEffect(() => {
        // 下拉滚动拉取数据追加到后面
        setMailListData([...mailListData, ...mailListResData]);
    }, [mailListResData]);

    // 加载更多回调
    const onLoadMore = e => {
        // 还可以拉取数据
        if (mailListData.length !== mailListTotal) {
            setparams({ ...params, pageNo: e });
        } else {
            message.warning('没有更多数据了');
        }
    };

    useEffect(() => {
        // 判断初始模态框是否打开
        const currentPath = pageTabUtil.getCurrentKey();
        if (!currentMail && currentPath === '/personal/message/mails') {
            setVisible(true);
        } else {
            // 更新下绑定信息
            dispatch({
                type: 'user/fetchMailBindInfo',
                payload: { userCode }
            });
        }
    }, []);

    // 更新全局邮箱未读数量
    const updateMailPrompt = () => {
        dispatch({
            type: 'global/fetchMailPrompt',
            payload: {
                userCode
            }
        });
    };

    // 点击查看详情
    const [readParams, setReadParams] = useState(null);
    const { resData: readResData } = useSetMailRead(readParams);
    const handleMailInfo = e => {
        const { id, readFlag, subject } = e;
        // 未读更改状态
        if (readFlag === 0) {
            setReadParams({
                belongs: params.belongs,
                id
            });

            // 更改本地数据中相关id的阅读状态
            setMailListData(
                mailListData.map(item => {
                    const temp = item;
                    if (item.id === id) {
                        temp.readFlag = 1;
                    }
                    return temp;
                })
            );
        }
        setMailId(id);
        setInfoSubject(subject);
    };

    // 已读完成
    useEffect(() => {
        if (readResData) {
            updateMailPrompt();
        }
    }, [readResData]);

    // 清除数据
    const clearMailData = () => {
        setMailListResData([]);
        setMailId(null);
        setInfoSubject(null);
        setMailListData([]);
    };

    // 点击收邮件，从服务器刷新发件箱和收件箱邮件列表，切换到收件箱第一页
    const [mailsPullQuery, setMailsPullQuery] = useState(null);
    const [mailsPullLoading, mailsPullData] = usePullList(mailsPullQuery);
    const handleRefreshClick = () => {
        setMailsPullQuery({
            belongs: params.belongs
        });
    };
    useEffect(() => {
        if (_.size(mailsPullData) > 0) {
            if (mailsPullData.msg.length > 0) {
                message.warn(mailsPullData.msg);
            } else {
                notification.success({
                    message: (
                        <div>
                            收到<b style={{ color: '#f00' }}> {mailsPullData.fetchCount || 0} </b>条新邮件
                        </div>
                    ),
                    placement: 'bottomRight',
                    duration: 5
                });
                clearMailData();
                setparams({ ...params, mailType: 'in', pageNo: 1 }); // 切换到收件箱第一页
                updateMailPrompt();

                // 埋点
                eventTrack({
                    eventName: 'check_button_click',
                    eventProps: { receive_email_num: mailsPullData.fetchCount }
                });
            }
        }
    }, [mailsPullData]);

    // 切换邮箱
    const handleMailChange = e => {
        clearMailData();
        localStorage.setItem('currentMail', e);
        setCurrentMail(e);
        setparams({ ...params, belongs: e, pageNo: 1 });
    };

    const operations = (
        <div>
            <Button
                disabled={!currentMail || mailsPullLoading}
                style={{ marginRight: 16 }}
                onClick={() => {
                    handleRefreshClick();
                    eventTrack({
                        eventName: 'personal_message_mails_receive_click',
                        pageName: 'personal_message_mails'
                    });
                }}
            >
                <Icon type={mailsPullLoading ? 'loading' : 'mail'} /> {mailsPullLoading ? '邮件拉取中...' : '收邮件'}
            </Button>
            <Button
                type="primary"
                disabled={!currentMail}
                onClick={async () => {
                    const path = '/personal/message/mails/create';
                    // pageTabUtil.openTab(path);

                    // 埋点
                    await eventTrack({
                        eventName: 'personal_message_mails_send_click',
                        pageName: 'personal_message_mails'
                    });
                    history.push(path);
                }}
            >
                <Icon type="edit" /> 写邮件
            </Button>
        </div>
    );
    return (
        <>
            <MailSwitchBar
                data={mailBindList}
                promptCount={mailPromptCount}
                onChange={handleMailChange}
                currentMail={currentMail}
            />
            <Card
                className={styles.mailListWrap}
                title={
                    <Menu
                        mode="horizontal"
                        style={{ borderBottom: 0 }}
                        selectedKeys={params.mailType}
                        onClick={e => {
                            // 切换邮箱类型显示相应类型第一页的数据
                            clearMailData();
                            setparams({ ...params, mailType: e.key, pageNo: 1 });

                            // 埋点
                            if (e.key === 'in') {
                                eventTrack({ eventName: 'personal_message_mails_inbox_click', pageName: 'personal_message_mails' });
                            } else {
                                eventTrack({ eventName: 'personal_message_mails_outbox_click', pageName: 'personal_message_mails' });
                            }
                        }}
                    >
                        <Menu.Item key="in" disabled={!currentMail}>
                            收件箱
                        </Menu.Item>
                        <Menu.Item key="out" disabled={!currentMail}>
                            发件箱
                        </Menu.Item>
                    </Menu>
                }
                bordered={false}
                bodyStyle={{ padding: 0 }}
                extra={operations}
            >
                <div className={styles.bodyWrap}>
                    {/* 邮件列表 */}
                    <div
                        style={{
                            width: 384,
                            height: '100%',
                            overflow: 'auto',
                            borderRight: '1px solid #f0f0f0'
                        }}
                    >
                        <Spin spinning={mailListLoading}>
                            <MailingList
                                query={params}
                                data={mailListData} // 列表数据源
                                setSourceData={setMailListData} // 更新列表数据源
                                curData={mailListResData} // 当前拉取的数据
                                onLoadMore={onLoadMore} // 加载更多
                                hasMore={mailListData.length !== mailListTotal} // 是否加载完成，数据源总条数和接口返回条数判断
                                onClick={handleMailInfo} // 点击具体邮件回调
                                defaultId={mailId} // 默认选中的邮件
                                setDefaultId={setMailId} // 设置默认选中的邮件
                                setReadParams={setReadParams}
                            />
                        </Spin>
                    </div>
                    {/* 邮件内容 */}
                    <div
                        style={{
                            flex: 1,
                            height: '100%',
                            overflow: 'hidden'
                        }}
                    >
                        <MailContent mailId={mailId} query={params} subject={infoSubject} />
                    </div>
                </div>
            </Card>

            <MailBindForm
                visible={visible}
                onOk={e => {
                    const { email } = e;
                    setCurrentMail(email);
                    setVisible(false);
                }}
                onCancel={() => {
                    setVisible(false);
                }}
            />
        </>
    );
};
export default connect(({ user, global }) => ({
    user: user.currentUser,
    mailBindList: user.mailBindList,
    mailPromptCount: global.mailPromptCount
}))(MailList);
